package com.nzd.slsharing.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nzd.slsharing.exception.CustomExpiredException;
import com.nzd.slsharing.mapper.UserMapper;
import com.nzd.slsharing.pojo.RegisterForm;
import com.nzd.slsharing.pojo.User;
import com.nzd.slsharing.pojo.LoginForm;
import com.nzd.slsharing.service.UserService;
import com.nzd.slsharing.util.EncryptionUtils;
import com.nzd.slsharing.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    /**
     * 超级管理员登录
     * @param loginForm
     * @return
     */
    @Override
    public User login(LoginForm loginForm) {
        //创建 QueryWrapper 对象
//        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        //拼接条件查询
        queryWrapper.eq(User::getPassword, loginForm.getUsername());
        //转换成密文进行查询
        queryWrapper.eq(User::getPassword, MD5.encrypt(loginForm.getPassword()));
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByStudentIdAndUP(String studentId, String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", password);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public User getUserByStudentId(String studentId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 注册
     * @param registerForm 注册表单
     * @return 返回注册结果：1 成功，0 失败
     */
    @Override
    public Integer register(RegisterForm registerForm) {
        Integer num = 0;

        try {
            // 判断前端表单空字符
            if (StringUtils.isEmpty(registerForm.getStudentId()) ||
                    StringUtils.isEmpty(registerForm.getUsername()) ||
                    StringUtils.isEmpty(registerForm.getPassword()) ||
                    StringUtils.isEmpty(registerForm.getConfirmPassword()) ||
                    StringUtils.isEmpty(registerForm.getSchool())) {
                throw new CustomExpiredException("请输入完整信息！");
            }

            // 校验密码是否一致
            if (!registerForm.getPassword().equals(registerForm.getConfirmPassword())) {
                throw new CustomExpiredException("密码与确认密码不一致！");
            }

            // 查询是否已存在相同用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("student_id", registerForm.getStudentId());
            User existingUser = baseMapper.selectOne(queryWrapper);

            if (existingUser != null) {
                throw new CustomExpiredException("用户已存在!");
            } else {
                // 用户不存在，进行注册
                User user = new User();
                user.setUsername(registerForm.getUsername());

                // 密码加密：使用更安全的加密方式，如 bcrypt
                String encryptedPassword = EncryptionUtils.encrypt(registerForm.getPassword());
                user.setPassword(encryptedPassword);
                user.setStudentId(registerForm.getStudentId());
                user.setUserRole(1); // 用户默认权限为普通用户
                user.setCreateTime(new Date());
                user.setSchool(registerForm.getSchool());
                user.setAge(registerForm.getAge());

                // 插入用户到数据库
                if (baseMapper.insert(user) > 0) {
                    num = 1; // 注册成功
                } else {
                    num = 0; // 注册失败
                }
            }
        } catch (Exception e) {
            e.printStackTrace();  // 打印异常堆栈
            throw new CustomExpiredException("注册失败，发生错误：" + e.getMessage());
        }

        return num;
    }



    // 查询用户名学号
    @Override
    public User getUserByNameAndStudentId(String username,String studentId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 分页获取所有Admin信息【带条件】
     */
    @Override
    public IPage<User> getUsers(Page<User> pageParam, String adminName) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(adminName)){
            lambdaQueryWrapper.like(User::getPassword, adminName);
        }
        lambdaQueryWrapper.orderByDesc(User::getId);
        lambdaQueryWrapper.orderByAsc(User::getPassword);
        return baseMapper.selectPage(pageParam, lambdaQueryWrapper);
    }

    /**
     * @param studentId
     * @return
     */
    @Override
    public Integer removeByStudentId(String studentId) {
        QueryWrapper<User> queryWrapper=new QueryWrapper();
        queryWrapper.eq("student_id",studentId);
        return  baseMapper.delete(queryWrapper);
    }
}
